# -*- coding: UTF-8 -*-
# Python 2.x引入httplib模块
# import httplib
# Python 3.x引入http.client模块
# -*- coding: UTF-8 -*-
# Python 2.x引入httplib模块。
# import httplib
# Python 3.x引入http.client模块。
from functools import reduce

from pydub import AudioSegment
from pydub.utils import db_to_float

podcast = AudioSegment.from_mp3("")
average_loudness = podcast.rms
silence_threshold = average_loudness * db_to_float(-30)
podcast_parts = (ms for ms in podcast if ms.rms > silence_threshold)
podcast = reduce(lambda a, b: a + b, podcast_parts)
podcast.export("psdrocessed.wav", format="wav")
# import  datetime
# import requests as rs
# def specialback(text):
#     # 判断是否忙碌
#
#     notnone = ()
#     # 脏话
#     global baiduapitoken
#     if notnone == ():
#         try:
#
#             urllink = 'https://aip.baidubce.com/rest/2.0/antispam/v2/spam?access_token=' + str(baiduapitoken)
#             boby = {'content': str(text)}
#             req = rs.post(urllink, data=boby, timeout=3)
#             # req = rs.post(urllink, timeout=60)
#
#             data = req.json()
#             # print('data',data)
#             req.close()
#             if 'error_code' in data.keys():
#
#
#                 if str(data['error_code']) == '111' or str(data['error_code']) == '110':
#                     # apitaken = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=9goGmAIOyCEEGjF8edHO9Syu&client_secret=z5cOOdIys39Y7zV9CNiGoYkWDyGlQuzZ'
#                     apitaken = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=wVijsc3uL8R0hWvc8nK3SbAK&client_secret=hMt8Ij0i0xAy85o8vYTf4O0FdSRA6kYe'
#                     req = rs.post(apitaken)
#                     apidata = req.json()
#                     # print('apidata',apidata)
#
#                     if 'access_token' in apidata.keys():
#                         baiduapitoken = apidata['access_token']
#             if str(data['result']['spam']) == '1':
#               print('kkkk')


# POST请求方式
# processPOSTRequest(appKey, token, text, audioSaveFile, format, sampleRate)
# import json
# ss = {'TaskId': '59d0efa3fd4f11ea89f28398cf0a5707', 'RequestId': '07CBCF94-CFC8-4196-B96F-AE500817ADD0', 'StatusText': 'SUCCESS', 'BizDuration': 0, 'SolveTime': 1600832784593, 'StatusCode': 21050000}
# if 'Result' not in ss:
#     print('ffffffff')
# ss["Result"] =   {'Words': [], 'Sentences': []}
# print(ss)
# import datetime
# import base64
# the_sig_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
# id = "N00000052307"
# apis = "0cfe5870-fee6-11ea-acb2-d19ca7543771".upper()
# the_au = str(id)+":"+str(the_sig_time)
# print(base64.b64encode(the_au.encode()).decode())
# import time,datetime
# print(time.strptime('12:30', '%H:%M'))
# print(datetime.datetime.strptime('2020-11-11 12:30:22', '%H:%M').date())
# the_begintime = time.strptime(str('2020-11-11 12:30:22'), "%H:%M")
# the_endtime = time.strptime(str('2020-11-11 14:30:22'), "%H:%M")
# the_now_tome = time.strptime(str(time.strftime("%H:%M")), "%H:%M")
# if the_begintime<the_now_tome<=the_endtime:
#     print('kky')
# import re
# s = "呃你好请问今天是你们有打电话给我吧我是刘慧"
# reg=r'号码是空号,哪点事没事,请.*(?:按|拨)(?:分机号|专用号|零|一|二|三|四|五|六|七|八|九|井|星|0|1|2|3|4|5|6|7|8|9),(?:运营部|业务部|社保申请|社保咨询|发送|重录).*(?:请拨|请按),(?:拨|播|按|查|输入|打|留言|转接|重试|重新|重启|重拨|重播|重按|重录|重查|重复|挂机|丑露).*请,请.*(?:拨|播|按|查|输入|打|留言|转接|重试|重新|重启|重拨|重播|重按|重录|重查|挂机),超时.*(?:重试|重新|重启|重拨|重播|重按|重录|重查|重复|挂机|次数),(?:按键|输入|收入|叔叔|请求|查|点击).*超时,请查.*(?:拨|播|按|输入|收入|查|询|证|明),(?:密码|错误|有误|不正确|重复).*输入,留言(?:将收取|请挂机|通过短信),机主.*(?:秘书|不在|助力|助理),(?:再|在)跟我.*要(?:告诉|投诉|警告|报警|告).*你,报警抓你,坐牢,监狱,垃圾,宝宝'
# reg =reg.replace(",","|")
# pipe_word=re.compile(reg)
# worklist=re.findall(pipe_word,s)
# print(worklist)
# pp = s.partition(worklist[0])
# print('pp',pp)
# print(pp[0]+pp[1])
# import math
# print(math.ceil(5000 / 1000))
# pipe_word=re.split(reg,s)
# print('33',pipe_word)
# worklist=re.findall(pipe_word,s)
# print(worklist)
# s = "1,2,3"
# fs = s.strip(',').split(',')
# f =tuple([int(f) for f in  fs])
# print(f,type(f))
# from gevent import monkey
# monkey.patch_all(thread=False)
# quality_data_dict = [{'a':1,'b':1},{'a':2,'b':2},{'a':3,'b':3},{'a':4,'b':4},{'a':5,'b':5},]
# for i,quality_data in enumerate(quality_data_dict):
#     print(i,quality_data,quality_data_dict)
#     if i/2 ==0:
#         quality_data_dict.append( {'a': quality_data['a'], 'b':quality_data['b']} )
# tenxunyun
# -*- coding: utf-8 -*-
# import re#|在吗*@s#(你好|在吗)
# import memcache
# import sys
# import time
# import datetime
# import math
# d = '/home/Fzrobot/FA20200721/F1595322111752013.wav'
# print(d.encode("ASCII"))
# coding: utf-8

# import os
# from ftplib import FTP
#
# def ftp_connect(host, username, password):
#     ftp = FTP()
#     # ftp.set_debuglevel(2)
#     ftp.connect(host, 222)
#     ftp.login(username, password)
#     return ftp
#
# """
# 从ftp服务器下载文件
# """
# def download_file(ftp, remotepath, localpath):
#     bufsize = 1024
#     fp = open(localpath, 'wb')
#     ftp.retrbinary('RETR ' + remotepath, fp.write, bufsize)
#     ftp.set_debuglevel(0)
#     fp.close()
#
# """
# 从本地上传文件到ftp
# """
# def upload_file(ftp, remotepath, localpath):
#     bufsize = 1024
#     fp = open(localpath, 'rb')
#
#     ftp.storbinary('STOR ' + remotepath, fp, bufsize)
#     ftp.set_debuglevel(0)
#     fp.close()
#
#
# if __name__ == "__main__":
#     ftp = ftp_connect("47.94.89.73", "f6tp", "fq333")
#     # download_file(ftp, r"utils.py", r"D:\txt\utils.py")
#     #调用本地播放器播放下载的视频
#     # os.system('start "C:\Program Files\Windows Media Player\wmplayer.exe" "C:/Users/Administrator/Desktop/test.mp4"')
#     upload_file(ftp, r"trainers.py", r"D:\Pro\Chatterbot\ChatterBotmaster\chatterbot\trainers.py")
#
#     ftp.quit()


# from apscheduler.schedulers.blocking import BlockingScheduler
# from datetime import datetime
# # 输出时间
# def job():
#     print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
#     return []
# # BlockingScheduler
# scheduler33 = BlockingScheduler()
# scheduler33.add_job(job, 'cron', hour=10, minute=47, second=00)
# scheduler33.start()

# from apscheduler.schedulers.background import BlockingScheduler
#
#
# # 将要被定时执行的任务
# def task(s):
#     print(s)
#
#
# if __name__ == '__main__':
#     # 初始化调度器
#     background_scheduler = BlockingScheduler()
#
#     # 添加任务作业，args()中最后一个参数后面要有一个逗号，本任务设置在每天凌晨1:00:00执行
#     background_scheduler.add_job(task, 'cron', hour='10', minute='39', second='00', args=("hello",))
#
#     # 启动调度器，到点task就会被执行啦
#     background_scheduler.start()

# d = -3.6-4
# print(d)
# mc = memcache.Client(['47.94.89.73:13853'], debug=True)#测试库
# def if_exist(key):
#     try:
#         ifexist = mc.get(key)
#         #不存在None
#         print(ifexist,type(ifexist))
#         return ifexist
#     except Exception as e:
#         print(343)
# if_exist('dddd')
# text = 'kkkks#没问题@s##好的@s#没问题我觉得是好的' #.*可以|好
# pipe_word = re.compile("s#{1,}.*(?:你好|好的).*\@s#{1,}.*(?:在吗|没.*题).*(?:可以|好)")
# worklist = re.findall(pipe_word,text)
# # wort = re.findall(r'.*(?:在吗|没问题).*(?:可以|好)','可以@s#没问题我觉得是好的' )
# print(worklist)
# text = 's#先生。c#喂。c#喂。c#对对对。' #.*可以|好
# pipe_word = re.compile("c#{1,}.*喂c#{1,}.*对")
# worklist = re.findall(pipe_word,text)
# # wort = re.findall(r'.*(?:在吗|没问题).*(?:可以|好)','可以@s#没问题我觉得是好的' )
# print(worklist)
# Year = r'[12]\d{3}'
# Month = r'Jan|Feb|Mar'
# Day = r'\d{2}'
# HourMins = r'\d{2}:\d{2}'
# Date = r'%s %s, %s, %s' % (Month, Day, Year, HourMins)
# DateR = re.compile(Date)
# print(DateR)
# from threading import Timer
# import time
# li1 = [1,2,3,4,5,6]
# li2 = [2,3,4,5,6,7]
# for i in li2:
#     print(2222)
#     for j in li1:
#         if j ==4:
#             break
#         print(11111)

# li = [1,2,3,4]
# print(str(li))
# import sched, time,datetime
# s = sched.scheduler(time.time, time.sleep)
# print(datetime.datetime.now())
# i = 0
# def do_something(sc,num):
#     global i
#     print("Doing stuff..."+num)
#     # do your stuff
#     if i < 5:
#         i = i + 1
#         s.enter(5, 0, do_something, (sc,num))
#         print(datetime.datetime.now())
#     else:
#         print('end')
#
# s.enter(3, 0, do_something, (s,'b'))
# s.enter(5, 0, do_something, (s,'a'))
# s.run()
# timer_interval = 1
#
#
# def delayrun(a,b,c,d):
#     print('running',a,b,c,d)
#
#
# t = Timer(1, delayrun)
# t.start()
# while True:
#     time.sleep(0.1)
#     print('main running')

# def main(sql):
#     select(sql)
#
# def select(sql):
#     print(sql)
#
#
# d = None
# if d:
#     print('ddddd')

# from multiprocessing import Process,Value,Lock
# from multiprocessing.managers import BaseManager
# class Employee(object):
#     def __init__(self,name,salary):
#         self.name=name
#         self.salary=Value('i',salary)
#     def increase(self):
#         self.salary.value+=100
#     def getPay(self):
#         return self.name+':'+str(self.salary.value)
# class MyManager(BaseManager):
#     pass
# def Manager2():
#     m=MyManager()
#     m.start()
#     return m
# MyManager.register('Employee',Employee)
#
# def func1(em,lock):
#     with lock:
#         em.increase()
#
# if __name__ == '__main__':
#     manager=Manager2()
#     em=manager.Employee('zhangsan',1000)
#     lock=Lock()
#     proces=[Process(target=func1,args=(em,lock))for i in range(10)]
#     for p in proces:
#         p.start()
#     for p in proces:
#         p.join()
#     print(em.getPay())

# from gevent.pool import Group
# import gevent,time
#
# def dd():
#     print('ddd')
# def intensive(n):
#     print('5666')
#     dd()
#     gevent.sleep(0)
#     print('333')
#     return 'r'
# ogroup = Group()
#
# for x in ogroup.imap(intensive, [1,2,3,4,5]):
#     print('ddd')
# coding:utf-8
# -*-coding:utf-8-*-


# import gevent
# from gevent.coros import BoundedSemaphore
#
# sem = BoundedSemaphore(2)
#
# def worker(n):
#     sem.acquire()
#     print('Worker %i acquired semaphore' % n)
#     gevent.sleep(0)
#     sem.release()
#     print('Worker %i released semaphore' % n)
#
# gevent.joinall([gevent.spawn(worker, i) for i in xrange(0, 6)])
# writetxt('TTS_data',str(x))
# !/usr/bin/env python
# coding:utf8
# Author: hz_oracle
# import requests
# #from guanjianzi import keylist as keys
# import re
# #from conMySql import ConDb
# from multiprocessing.dummy import Pool as ThreadPool
# import time
# start = time.time()
# s=requests.Session()
# #con=ConDb()
# def getlist(url):
#     print(url)
#     #time.sleep(1)
#     print('444')
#     return url
#         #sql='''  insert into urllist(source,urls,titles,keyname,keysum,date1) values('{}','{}','{}',"{}",'{}','{}') '''.format(title,y,z,guanjianzi,num,x)
#         #con.runSql(sql)
# if __name__ == '__main__':
#     urls = ['http://www.ndrc.gov.cn/xwzx/xwfb/index.html','http://www.ndrc.gov.cn/zwfwzx/zxgg/index.htmm','http://www.ndrc.gov.cn/zwfwzx/xzxknew/index.html','http://www.ndrc.gov.cn/zcfb/zcfbl/index.html','http://www.ndrc.gov.cn/zcfb/gfxwj/index.html','http://www.ndrc.gov.cn/zcfb/zcfbgg/index.html','http://www.ndrc.gov.cn/zcfb/zcfbghwb/index.html','http://www.ndrc.gov.cn/zcfb/zcfbtz/index.html','http://www.ndrc.gov.cn/zcfb/jd/index.html','http://www.ndrc.gov.cn/yjzq/index.html']
#     t=ThreadPool(5)
#
#     for url in urls:
#         t.apply_async(getlist,args=(url,))
#     t.close()
#     print(t.join())
#     end=time.time()
#     print('',end-start)
# sql1='select max(bat) from urllist limit 1'
# bat=con.runSql(sql1)[0][0]
# bat=int(bat)+1
# print(bat)
# sql2="update urllist set bat='{}'".format(bat)
# con.runSql(sql2)


# print('successful ',winner.successful())  # True
# print('successful ',loser.successful())   # False

# 这里可以通过raise loser.exception 或 loser.get()
# 来将协程中的异常抛出
# print(loser.exception)
# import gevent
# from gevent.pool import Group
#
# def intensive(n):
#     print(n,type(n))
#     gevent.sleep(3)
#     return 'task'
#
#
# ogroup = Group()
#
# for x in ogroup.imap(intensive,[[3,4,5],3,4]):
#     print(x)

# #import MySQLdb
# import requests
# import time
# import threading
# #import Queue
#
# from gevent import monkey; monkey.patch_all()
# import gevent
#
#
# class DbHandler(object):
#     def __init__(self, host, port, user, pwd, dbname):
#         self.host = host
#         self.port = port
#         self.user = user
#         self.pwd = pwd
#         self.db = dbname
#
#     def db_conn(self):
#         try:
#             self.conn = MySQLdb.connect(host=self.host, port=self.port, user=self.user, passwd=self.pwd, db=self.db, charset="utf8")
#             self.cursor = self.conn.cursor()
#             return 1
#         except Exception as e:
#             return 0
#
#     def get_urls(self, limitation):
#         # urls_list = list()
#         # sql = """select pic  from  picurltable limit  %s""" % limitation
#         # try:
#         #     self.cursor.execute(sql)
#         #     fetchresult = self.cursor.fetchall()
#         #     for line in fetchresult:
#         #         urls_list.append(line[0])
#         # except Exception as e:
#         #     print u"数据库查询失败:%s"  % e
#         #     return []
#         # return urls_list
#         return [1,2,3,4,5,6,7,8,9]
#
#     def db_close(self):
#         self.conn.close()
#
#
# def get_pic(url):
#     print('get_pic',url)
#     return "ok"

# begintime =1596695081124
# endtime = 1596695087124
# word=13
# sessionid=11
# alltime = round((endtime - begintime) / 1000, 2)
# minute_count = int((60 * word) / alltime)
# print(minute_count)
# from dateutil.parser import parse
# a = parse('2017-10-01 12:12:12')
# b = parse('2017-10-01 12:1:10')
# print((a-b).days)
# print((a-b).seconds)
# print(datetime.datetime.strptime(str(datetime.datetime.now()), '%H:%M'))
# def main():
#     start_time = time.time()
#     db_obj = DbHandler(host='127.0.0.1', port=3306, user='root', pwd='123456', dbname='pic')
#     # db_obj.db_conn()
#     url_list = db_obj.get_urls(100)
#     print(gevent.joinall([gevent.spawn(get_pic,url) for url in url_list]))
#
#     end_time = time.time()
#     costtime = float(end_time) - float(start_time)
#     print(costtime)
#     print("download END")
#
# def maind():
#     start_time = time.time()
#     db_obj = DbHandler(host='127.0.0.1', port=3306, user='root', pwd='123456', dbname='pic')
#     # db_obj.db_conn()
#     url_list = db_obj.get_urls(100)
#     for i in url_list:
#         get_pic(i)
#
#    # gevent.joinall([gevent.spawn(get_pic,url) for url in url_list])
#
#     end_time = time.time()
#     costtime = float(end_time) - float(start_time)
#     print(costtime)
#     print("download END")
# if __name__ == "__main__":
#
#
#     main()
#     maind()


# class Threaddata(threading.Thread):
#     def __init__(self, text,ci,i):
#         threading.Thread.__init__(self)
#         self.text=text
#         self.ci=ci
#         self.q = q
#
#     def run(self):
#         get_results(text,ci,i)
#         # do something
# class Controller(threading.Thread):
#     def __init__(self, threads):
#         threading.Thread.__init__(self)
#         self.daemon = True
#         self.threadList = threads
#
#     def run(self):
#         for each in self.threadList:
#             each.start()
#         while True:
#             for a in range(3):
#                 if not self.threadList[a].isAlive():
#                     self.threadList[a] = Threaddata(a,a,a)
#                     self.threadList[a].start()
#
#
# threads = []
# for i in range(3):
#         t = Threaddata(i,i,i)
#         threads.append(t)
# c = Controller(threads)
# c.start()
# c.join()
# import threading
# import queue
# import time
# import random
#
# '''
# 需求：主线程开启了多个线程去干活，每个线程需要完成的时间
# 不同，但是在干完活以后都要通知给主线程
# 多线程和queue配合使用，实现子线程和主线程相互通信的例子
# '''
# q = queue.Queue()
# threads=[]
# class MyThread(threading.Thread):
#     def __init__(self,q,t,j):
#         super(MyThread,self).__init__()
#         self.q=q
#         self.t=t
#         self.j=j
#
#     def run(self):
#         time.sleep(self.j)
#         # 通过q.put()方法，将每个子线程要返回给主线程的消息，存到队列中
#         self.q.put("我是第%d个线程，我睡眠了%d秒,当前时间是%s" % (self.t, self.j,time.ctime()))
#
#
#
# '''
# # 生成15个子线程，加入到线程组里，
#     # 每个线程随机睡眠1-8秒（模拟每个线程干活时间的长短不同）
# '''
#
# for i in range(15):
#    j=random.randint(1,8)
#    threads.append(MyThread(q,i,j))
#
# #    循环开启所有子线程
# for mt in threads:
#     mt.start()
# print('进程开启时间：%s'%(time.ctime()))
# '''
# 通过一个while循环，当q队列中不为空时，通过q.get()方法，
# 循环读取队列q中的消息，每次计数器加一，当计数器到15时，
# 证明所有子线程的消息都已经拿到了，此时循环停止
# '''
# count = 0
# while True:
#     if not q.empty():
#         print(q.get())
#         count+=1
#     if count==15:
#         break
